<template>
  <view class="device-manage-page">
    <!-- 顶部导航 -->
    <u-navbar title="我的设备" :auto-back="true" :border-bottom="true" />
    
    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stat-card">
        <view class="stat-item">
          <text class="stat-number">{{ deviceStats.total || 0 }}</text>
          <text class="stat-label">总设备</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ deviceStats.available || 0 }}</text>
          <text class="stat-label">可租赁</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ deviceStats.rented || 0 }}</text>
          <text class="stat-label">已租出</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ deviceStats.offline || 0 }}</text>
          <text class="stat-label">已下线</text>
        </view>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          v-for="tab in filterTabs" 
          :key="tab.value"
          class="filter-tab"
          :class="{ active: currentFilter === tab.value }"
          @click="setFilter(tab.value)"
        >
          <text class="tab-text">{{ tab.label }}</text>
          <text class="tab-count" v-if="tab.count > 0">({{ tab.count }})</text>
        </view>
      </view>
      
      <view class="filter-actions">
        <view class="action-btn" @click="showSortModal = true">
          <u-icon name="sort" size="16" color="#666" />
          <text class="action-text">{{ getSortText() }}</text>
        </view>
        <view class="action-btn" @click="refreshDevices">
          <u-icon name="reload" size="16" color="#666" />
        </view>
      </view>
    </view>

    <!-- 设备列表 -->
    <scroll-view 
      scroll-y 
      class="device-list"
      @scrolltolower="loadMoreDevices"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="devices.length === 0 && !loading" class="empty-state">
        <image src="/static/empty-devices.png" class="empty-image" mode="aspectFit" />
        <text class="empty-text">暂无设备</text>
        <text class="empty-desc">发布您的第一个设备开始赚取收益</text>
        <u-button type="primary" @click="goToUpload" class="upload-btn">
          发布设备
        </u-button>
      </view>
      
      <view v-else class="device-grid">
        <view 
          v-for="device in devices" 
          :key="device.id"
          class="device-card"
          @click="goToDeviceDetail(device.id)"
        >
          <view class="device-image-section">
            <image 
              :src="device.images?.[0] || '/static/placeholder-device.png'" 
              class="device-image"
              mode="aspectFill"
            />
            <view class="device-status" :class="getStatusClass(device.status)">
              {{ getStatusText(device.status) }}
            </view>
            <view class="device-actions">
              <view class="action-icon" @click.stop="editDevice(device.id)">
                <u-icon name="edit-pen" size="14" color="#fff" />
              </view>
              <view class="action-icon" @click.stop="deleteDevice(device.id)">
                <u-icon name="trash" size="14" color="#fff" />
              </view>
            </view>
          </view>
          
          <view class="device-info">
            <text class="device-title">{{ device.title }}</text>
            <text class="device-subtitle">{{ device.brand }} {{ device.model }}</text>
            <view class="device-meta">
              <text class="device-price">￥{{ device.dailyRent }}/天</text>
              <text class="device-location">{{ device.location?.city || '未知位置' }}</text>
            </view>
            <view class="device-stats">
              <text class="stat-text">浏览 {{ device.viewCount || 0 }}</text>
              <text class="stat-text">收藏 {{ device.favoriteCount || 0 }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMore && devices.length > 0" class="load-more">
        <u-loading-icon v-if="loadingMore" />
        <text v-else class="load-text">上拉加载更多</text>
      </view>
    </scroll-view>

    <!-- 浮动按钮 -->
    <view class="fab-section">
      <view class="fab-button" @click="goToUpload">
        <u-icon name="plus" size="24" color="#fff" />
      </view>
    </view>

    <!-- 排序弹窗 -->
    <u-popup v-model="showSortModal" mode="bottom" border-radius="20">
      <view class="sort-modal">
        <view class="modal-header">
          <text class="modal-title">排序方式</text>
          <u-icon name="close" @click="showSortModal = false" size="20" />
        </view>
        <view class="sort-options">
          <view 
            v-for="option in sortOptions" 
            :key="option.value"
            class="sort-option"
            :class="{ active: currentSort === option.value }"
            @click="setSort(option.value)"
          >
            <text class="option-text">{{ option.label }}</text>
            <u-icon v-if="currentSort === option.value" name="checkmark" size="16" color="#4A90E2" />
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import apiService from '@/api/index.js'

export default {
  data() {
    return {
      devices: [],
      deviceStats: {},
      loading: false,
      loadingMore: false,
      refreshing: false,
      hasMore: true,
      currentPage: 1,
      currentFilter: 'all',
      currentSort: 'createdAt',
      showSortModal: false,
      
      filterTabs: [
        { label: '全部', value: 'all', count: 0 },
        { label: '可租赁', value: 'AVAILABLE', count: 0 },
        { label: '已租出', value: 'RENTED', count: 0 },
        { label: '已下线', value: 'OFFLINE', count: 0 }
      ],
      
      sortOptions: [
        { label: '最新发布', value: 'createdAt' },
        { label: '价格从高到低', value: 'dailyRent-desc' },
        { label: '价格从低到高', value: 'dailyRent-asc' },
        { label: '浏览量最多', value: 'viewCount-desc' },
        { label: '收藏数最多', value: 'favoriteCount-desc' }
      ]
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  onShow() {
    // 每次显示时刷新数据
    this.refreshDevices()
  },
  
  methods: {
    async initPage() {
      await Promise.all([
        this.loadDeviceStats(),
        this.loadDevices()
      ])
    },
    
    async loadDeviceStats() {
      try {
        const stats = await apiService.device.getManagementStats()
        this.deviceStats = stats
        
        // 更新筛选标签数量
        this.filterTabs[0].count = stats.total || 0
        this.filterTabs[1].count = stats.available || 0
        this.filterTabs[2].count = stats.rented || 0
        this.filterTabs[3].count = stats.offline || 0
      } catch (error) {
        console.error('加载设备统计失败:', error)
        // 使用模拟数据
        this.deviceStats = {
          total: 5,
          available: 3,
          rented: 1,
          offline: 1
        }
      }
    },
    
    async loadDevices(append = false) {
      if (this.loading || this.loadingMore) return
      
      try {
        if (append) {
          this.loadingMore = true
        } else {
          this.loading = true
        }
        
        const params = {
          page: this.currentPage,
          limit: 10,
          status: this.currentFilter === 'all' ? undefined : this.currentFilter
        }
        
        // 处理排序参数
        const [sortBy, sortOrder] = this.currentSort.split('-')
        params.sortBy = sortBy
        params.sortOrder = sortOrder || 'desc'
        
        const result = await apiService.device.getMyDevices(params)
        const newDevices = result.data || result || []
        
        if (append) {
          this.devices = [...this.devices, ...newDevices]
        } else {
          this.devices = newDevices
        }
        
        this.hasMore = newDevices.length === 10
        this.currentPage = append ? this.currentPage + 1 : 1
        
      } catch (error) {
        console.error('加载设备列表失败:', error)
        uni.showToast({
          title: '加载设备列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.loadingMore = false
        this.refreshing = false
      }
    },
    
    async loadMoreDevices() {
      if (this.hasMore && !this.loadingMore) {
        this.currentPage++
        await this.loadDevices(true)
      }
    },
    
    async onRefresh() {
      this.refreshing = true
      this.currentPage = 1
      await Promise.all([
        this.loadDeviceStats(),
        this.loadDevices()
      ])
    },
    
    async refreshDevices() {
      this.currentPage = 1
      await this.onRefresh()
    },
    
    setFilter(filter) {
      this.currentFilter = filter
      this.currentPage = 1
      this.loadDevices()
    },
    
    setSort(sort) {
      this.currentSort = sort
      this.showSortModal = false
      this.currentPage = 1
      this.loadDevices()
    },
    
    getSortText() {
      const option = this.sortOptions.find(opt => opt.value === this.currentSort)
      return option ? option.label : '排序'
    },
    
    getStatusClass(status) {
      const statusMap = {
        'AVAILABLE': 'status-available',
        'RENTED': 'status-rented',
        'MAINTENANCE': 'status-maintenance',
        'OFFLINE': 'status-offline'
      }
      return statusMap[status] || 'status-unknown'
    },
    
    getStatusText(status) {
      const statusMap = {
        'AVAILABLE': '可租赁',
        'RENTED': '已租出',
        'MAINTENANCE': '维护中',
        'OFFLINE': '已下线'
      }
      return statusMap[status] || '未知状态'
    },
    
    goToDeviceDetail(deviceId) {
      uni.navigateTo({
        url: `/pages/devices/detail?id=${deviceId}`
      })
    },
    
    editDevice(deviceId) {
      uni.navigateTo({
        url: `/pages/profile/device-edit?id=${deviceId}`
      })
    },
    
    async deleteDevice(deviceId) {
      try {
        const result = await uni.showModal({
          title: '确认删除',
          content: '确定要删除这个设备吗？删除后无法恢复。',
          confirmText: '删除',
          confirmColor: '#ff4757'
        })
        
        if (result.confirm) {
          uni.showLoading({ title: '删除中...' })
          
          await apiService.device.deleteDevice(deviceId)
          
          uni.hideLoading()
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          // 刷新列表
          this.refreshDevices()
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        })
      }
    },
    
    goToUpload() {
      uni.navigateTo({
        url: '/pages/profile/device-upload'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.device-manage-page {
  background: $bg-color;
  min-height: 100vh;
}

.stats-section {
  padding: 24rpx;
}

.stat-card {
  background: $bg-white;
  border-radius: $border-radius-lg;
  padding: 32rpx 24rpx;
  display: flex;
  box-shadow: $box-shadow-light;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
}

.stat-number {
  font-size: 48rpx;
  font-weight: $font-weight-bold;
  color: $text-primary;
}

.stat-label {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.filter-section {
  padding: 0 24rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-tabs {
  display: flex;
  gap: 32rpx;
}

.filter-tab {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 0;
  border-bottom: 4rpx solid transparent;
  
  &.active {
    border-bottom-color: $primary-color;
  }
}

.tab-text {
  font-size: $font-size-base;
  color: $text-primary;
  
  .active & {
    color: $primary-color;
    font-weight: $font-weight-medium;
  }
}

.tab-count {
  font-size: $font-size-xs;
  color: $text-tertiary;
}

.filter-actions {
  display: flex;
  gap: 24rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  background: $bg-white;
  border-radius: $border-radius-base;
  box-shadow: $box-shadow-light;
}

.action-text {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.device-list {
  height: calc(100vh - 300rpx);
  padding: 0 24rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
}

.empty-text {
  font-size: $font-size-lg;
  color: $text-primary;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: $font-size-base;
  color: $text-secondary;
  margin-bottom: 48rpx;
  text-align: center;
}

.upload-btn {
  width: 240rpx;
  height: 80rpx;
}

.device-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
  padding-bottom: 120rpx;
}

.device-card {
  background: $bg-white;
  border-radius: $border-radius-lg;
  overflow: hidden;
  box-shadow: $box-shadow-light;
}

.device-image-section {
  position: relative;
  height: 200rpx;
}

.device-image {
  width: 100%;
  height: 100%;
}

.device-status {
  position: absolute;
  top: 16rpx;
  left: 16rpx;
  padding: 8rpx 16rpx;
  border-radius: $border-radius-sm;
  font-size: $font-size-xs;
  font-weight: $font-weight-medium;
  
  &.status-available {
    background: rgba(92, 184, 92, 0.9);
    color: white;
  }
  
  &.status-rented {
    background: rgba(217, 83, 79, 0.9);
    color: white;
  }
  
  &.status-maintenance {
    background: rgba(250, 173, 20, 0.9);
    color: white;
  }
  
  &.status-offline {
    background: rgba(108, 117, 125, 0.9);
    color: white;
  }
}

.device-actions {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  display: flex;
  gap: 8rpx;
}

.action-icon {
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.device-info {
  padding: 24rpx;
}

.device-title {
  font-size: $font-size-base;
  font-weight: $font-weight-medium;
  color: $text-primary;
  display: block;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.device-subtitle {
  font-size: $font-size-sm;
  color: $text-secondary;
  display: block;
  margin-bottom: 16rpx;
}

.device-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.device-price {
  font-size: $font-size-base;
  font-weight: $font-weight-medium;
  color: $primary-color;
}

.device-location {
  font-size: $font-size-xs;
  color: $text-tertiary;
}

.device-stats {
  display: flex;
  gap: 16rpx;
}

.stat-text {
  font-size: $font-size-xs;
  color: $text-tertiary;
}

.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32rpx 0;
}

.load-text {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.fab-section {
  position: fixed;
  bottom: calc(env(safe-area-inset-bottom) + 120rpx);
  right: 32rpx;
  z-index: 100;
}

.fab-button {
  width: 112rpx;
  height: 112rpx;
  background: $primary-color;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.3);
}

.sort-modal {
  background: $bg-white;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 60vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 2rpx solid $border-color;
}

.modal-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-bold;
  color: $text-primary;
}

.sort-options {
  padding: 32rpx;
}

.sort-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 2rpx solid $border-color;
  
  &:last-child {
    border-bottom: none;
  }
  
  &.active {
    .option-text {
      color: $primary-color;
      font-weight: $font-weight-medium;
    }
  }
}

.option-text {
  font-size: $font-size-base;
  color: $text-primary;
}
</style> 